from rest_framework.generics import GenericAPIView
from meiduo_admin.serializer.channel_serializer import *
from goods.models import *
from meiduo_admin.pages import MyPage
from rest_framework.response import Response
from meiduo_admin.serializer.spu_serializer import CategorysSerizliser


# GET /goods/channels/
class ChannelView(GenericAPIView):
    serializer_class = ChannelSerializer
    queryset = GoodsChannel.objects.all()
    pagination_class = MyPage

    """展示频道管理数据"""
    def get(self, request):
        channel = self.get_queryset()
        page = self.paginate_queryset(channel)
        if page:
            page_serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(page_serializer.data)
        serializer = ChannelSerializer(channel, many=True)
        return Response(serializer.data)

    # 新增频道
    def post(self, request):
        channel_obj = self.request.data
        serializer = self.get_serializer(data=channel_obj)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=201)


# GET goods/categories/
class ChannelClassifyView(GenericAPIView):
    serializer_class = CategorysSerizliser
    queryset = GoodsCategory.objects.filter(parent=None)

    """一级分类"""
    def get(self, request):
        classify = self.get_queryset()
        serializer = self.get_serializer(classify, many=True)
        return Response(serializer.data)


# GET goods/channel_types/
class ChannelGroupView(GenericAPIView):
    serializer_class = ChannelGroupSerializer
    queryset = GoodsChannelGroup.objects.all()

    def get(self, request):
        group = self.get_queryset()
        serializer = self.get_serializer(group, many=True)
        return Response(serializer.data)


# GET goods/channels/(?P<pk>\d+)/
class ChannelGroupOnlyView(GenericAPIView):
    serializer_class = ChannelSerializer
    queryset = GoodsChannel.objects.all()

    """获取单一数据"""
    def get(self, request, pk):
        channel_obj = self.get_object()
        serializer = self.get_serializer(channel_obj)
        return Response(serializer.data)

    def put(self, request, pk):
        channel_obj = self.get_object()
        serializer = ChannelSerializer(instance=channel_obj, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    def delete(self, request, pk):
        channel_obj = self.get_object()
        channel_obj.delete()
        return Response({})